public class Disj implements Stream {
    private Stream stm1;
    private Stream stm2;
    private Stream nextStream;
    private HistoryStream historyStream = new HistoryStream();

    public Disj(Stream stm1, Stream stm2) {
        this.stm1 = stm1;
        this.stm2 = stm2;
        this.nextStream = stm1;
    }

    public String next() {
        String res = historyStream.next();
        if (res == null) {
            res = getFromStreams();
        }
        return res;
    }

    private String getFromStreams() {
        String res = nextStream.next();
        switchStreams();
        if (res == null) {
            res = nextStream.next();
        }
        historyStream.add(res);
        return res;
    }

    private void switchStreams() {
        if (nextStream == stm1) {
            nextStream = stm2;
        } else {
            nextStream = stm1;
        }
    }

    public String prev() {
        return historyStream.prev();
    }

    public void reset() {
        stm1.reset();
        stm2.reset();
        historyStream.reset();
        nextStream = stm1;
    }
}
